package com.sxfq.loansupermarket.backsystem.modular.arrival.service.impl;

import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.MembersUser;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.MemberProductService;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.FirstCustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.ScoreDealInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.DoctorOperationInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerDetailsService;

import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional
public class CustomerDetailsServiceImpl implements ICustomerDetailsService {

    @Autowired
    private MemberProductService memberProductService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    ICustomerService customerService;

    @Autowired
    private SqlMapper sqlMapper;

    public CustomerInfo selectOneById(String id) {
        String sql = "select " +
                " (CASE t2.customer_sex  WHEN 1 THEN '男' WHEN 2 THEN '女' ELSE '未知' END ) as sex ," +
                " (CASE t2.marital_status WHEN 1 THEN '已婚' WHEN 2 THEN '未婚' WHEN 3 THEN '离异' ELSE '未知' END ) as maritalStatusName ," +
                "t2.* from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t2 where id= '" + id + "';";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        return customerInfo;
    }

    public int intodayOperation(CustomerInfo customerInfo) {
        String selectsql = "select id from today_operation_info where reservations_id='" + customerInfo.getReservationsId() + "' and " +
                " left(operation_time,10)='" + DateTimeKit.now().substring(0, 10) + "' and operation_people='" + ShiroKit.getUser().getAccount() + "' " +
                " and store='" + customerInfo.getArrivalStore() + "'";
        List<DoctorOperationInfo> doctorOperationInfo = sqlMapper.selectList(selectsql, DoctorOperationInfo.class);
        if (doctorOperationInfo.size() == 0) { //是否操作过该患者
            String insertSql = " INSERT INTO today_operation_info (customer_id,reservations_id,szm,operation_people,customer_name, " +
                    " customer_sex,customer_age, customer_phone,store,operation_time) values  " +
                    " ('" + customerInfo.getId() + "','" + customerInfo.getReservationsId() + "','" + customerInfo.getSzm() + "','" + ShiroKit.getUser().getAccount() + "','" + customerInfo.getCustomerName() + "','" + customerInfo.getCustomerSex() + "', " +
                    " '" + customerInfo.getCustomerAge() + "','" + customerInfo.getCustomerPhone() + "','" + customerInfo.getArrivalStore() + "','" + DateTimeKit.now() + "') ";
            return sqlMapper.insert(insertSql);//插入 今日操作数据 前台
        } else {
            String updatesql = "update today_operation_info set operation_time='" + DateTimeKit.now() + "' where reservations_id='" + customerInfo.getReservationsId() + "' and " +
                    " left(operation_time,10)='" + DateTimeKit.now().substring(0, 10) + "' and operation_people='" + ShiroKit.getUser().getAccount() + "' " +
                    " and store='" + customerInfo.getArrivalStore() + "'";
          return   sqlMapper.update(updatesql);
        }
    }

    public String  getorthodonticNumber(String reservationsId) {
        String orthodonticNumber="";
        String sql = "select t1.id as id,t1.operation_time as operationTime,t1.orthodontic_number as orthodonticNumber " +
                " from " +  redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"deal_info",0) + " t1 left join " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"pay_service_info",0) + " t2 on t1.pay_service_id=t2.id " +
                " where t1.reservations_id='" + reservationsId + "' " +
                " and orthodontic_number is not null and orthodontic_number!='' and t1.deal_status='已结账' group by orthodontic_number";
        List<PayServicedInfo> payServiceInfoList = sqlMapper.selectList(sql, PayServicedInfo.class);
        for (PayServicedInfo info : payServiceInfoList) {
            if (StringUtil.isNotEmpty(info.getOrthodonticNumber())) {
                orthodonticNumber = info.getOrthodonticNumber();
            }
        }
        return orthodonticNumber;
    }

    //最近一次患者信息
    public CustomerInfo selectOneByReservationsId(String reservationsId) {
        String sql = "select " +
                " (CASE t2.customer_sex  WHEN 1 THEN '男' WHEN 2 THEN '女' ELSE '未知' END ) as sex ," +
                " (CASE t2.marital_status WHEN 1 THEN '已婚' WHEN 2 THEN '未婚' WHEN 3 THEN '离异' ELSE '未知' END ) as maritalStatusName," +
                " t2.* from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " t2 " +
                " where reservations_id= '" + reservationsId + "' order by arrival_time desc limit 0,1;";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql, CustomerInfo.class);
        return customerInfo;
    }

    public ReservationsInfo getReservationsInfoList(String reservationsId){
        String sqlresrvationsc = "select id from reservations_infosc where id='" + reservationsId + "' limit 0,1";
        ReservationsInfo reservationscInfo = sqlMapper.selectOne(sqlresrvationsc, ReservationsInfo.class);
        if (reservationscInfo != null) {
            String reservationsInfosql = "select " +
                    " (CASE t2.customer_sex  WHEN 1 THEN '男' WHEN 2 THEN '女' ELSE '未知' END ) as sex ," +
                    " t2.* from reservations_infosc t2 where id='" + reservationsId + "' limit 0,1";
            ReservationsInfo reservationsInfo = sqlMapper.selectOne(reservationsInfosql, ReservationsInfo.class);
            reservationsInfo.setHuifang(reservationscInfo.getHuifang());
            return reservationsInfo;
        }
        return null;
    }

    public FirstCustomerInfo firstVisitInformation(String reservationsId) {
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsId + "' ";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        String customerTablesd = "";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                customerTablesd += "select id,appointment_pay_service,arrival_time,archiving,field_tc from " + head + "customer_info t where reservations_id='" + reservationsId + "' and arrival_time is not null";
            } else {
                customerTablesd += "select id,appointment_pay_service,arrival_time,archiving,field_tc " +
                        "from " + head + "customer_info t where reservations_id='" + reservationsId + "' " +
                        "and arrival_time is not null  union ";
            }
        }
        if (abbreviationList.size() == 0) {
            return null;
        }
        FirstCustomerInfo customerInfoFirst = customerService.selectOneByReservationsIdFirst(reservationsId, customerTablesd);  //首次到店患者信息
        return customerInfoFirst;
    }

    public CustomerInfo firstVisitInformations(String reservationsId) {
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsId + "' ";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        String customerTablesd = "";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                customerTablesd += "select * from " + head + "customer_info t where reservations_id='" + reservationsId + "' and arrival_time is not null";
            } else {
                customerTablesd += "select * " +
                        "from " + head + "customer_info t where reservations_id='" + reservationsId + "' " +
                        "and arrival_time is not null  union ";
            }
        }
        if (abbreviationList.size() == 0) {
            return null;
        }
        CustomerInfo customerInfo = customerService.selectOneByReservationsIdFirsts(reservationsId, customerTablesd);  //首次到店患者信息
        return customerInfo;
    }

    public List<CustomerInfo> visitRecords(String reservationsId) {
        //到过的店
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsId + "' ";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        String customerTables = "";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                customerTables += "select customer_name as customerName, left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,19) as startTime,t.id as id,t.remarks_reservation as remarksReservation," +
                        "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.arrival_status as arrivalStatus," +
                        "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status," +
                        "t.appointment_pay_service as appointmentPayService " +
                        "from " + head + "customer_info t where reservations_id='" + reservationsId + "' ";
            } else {
                customerTables += "select customer_name as customerName, left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,19) as startTime,t.id as id,t.remarks_reservation as remarksReservation," +
                        "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.arrival_status as arrivalStatus," +
                        "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status," +
                        "t.appointment_pay_service as appointmentPayService " +
                        "from " + head + "customer_info t where reservations_id='" + reservationsId + "' union ";
            }
        }
        if (abbreviationList.size() == 0) {
            return null;
        }
        //就诊记录
        String sql11 = "select * from (" + customerTables + ") t order by t.startTime desc";
        List<CustomerInfo> customerInfoList = sqlMapper.selectList(sql11, CustomerInfo.class);
        for (CustomerInfo infos : customerInfoList) {
            infos.setOutpatientName(ShiroKit.getUser().getOutpatientName());
            if (infos.getStartTime() != "" && infos.getStartTime() != null) {
                infos.setStartTimeOne(infos.getStartTime().substring(0, 10));
                infos.setStartTimeTwo(infos.getStartTime().substring(11, infos.getStartTime().length()));
            }
        }
        return customerInfoList;
    }

    public List<PayServicedInfo> unclosedRecords(String reservationsId) {
        //成交记录 ,结账记录
        String sqlno = "SELECT t1.id AS id,t1.customer_id AS customerId,t1.reservations_id AS reservationsId,t1.tc_name as tcName ,t1.outpatient_name AS outpatientName," +
                " t1.deal_status AS dealStatus, left(t1.get_time,19) as getTime,t1.operation_time as operationTime, sum(t1.service_actual_pay) as serviceActualPay, " +
                " GROUP_CONCAT(DISTINCT t1.remarks) AS remarks,GROUP_CONCAT(DISTINCT t1.doctor) AS doctor" +
                " FROM " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"deal_info",0) + " t1 LEFT JOIN " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"pay_service_info",0) + " t2 ON t1.pay_service_id=t2.id" +
                " WHERE t1.reservations_id='" + reservationsId + "' AND (t1.deal_status='已开单' or t1.deal_status='待审核') " +
                " group by t1.get_time order by t1.get_time desc ";
        List<PayServicedInfo> NoPayServiceInfoList = sqlMapper.selectList(sqlno, PayServicedInfo.class);
        return NoPayServiceInfoList;
    }

    public List<TcInfo> getTcList() {
        String getListSql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                " where b.abbreviation='" + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"" + "' and c.name like CONCAT('%','tc','%') ";
        List<TcInfo> tcInfoList = sqlMapper.selectList(getListSql, TcInfo.class);
        return tcInfoList;
    }

    public ScoreDealInfo memberInformation(String reservationsId) {
        String sql = "select (select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from return_cash_info where reservations_id='" + reservationsId + "') as scoreBalance," +
                "(select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from score_deal where reservations_id='" + reservationsId + "') as jfbalancea ," +
                "(select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_orthodontics_deal a  where a.reservations_id='" + reservationsId + "') as orthodonticsMoney from dual";
        ScoreDealInfo scoreDealInfo = sqlMapper.selectOne(sql, ScoreDealInfo.class);
        String vipLevelName = memberProductService.getVipLevelName(reservationsId);
        scoreDealInfo.setVipLevelName(vipLevelName);
        String selsql = "select reservations_id,members_num from members_user where reservations_id='" + reservationsId + "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(selsql, MembersUser.class);
        String membersNum = "";
        if (membersUser != null) {
            membersNum = membersUser.getMembersNum();
        }
        scoreDealInfo.setMembersNum(membersNum);
        String getMoneyBalance = "select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_deal a " +
                " where a.reservations_id='" + reservationsId + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(getMoneyBalance, MembersUser.class);
        scoreDealInfo.setMoneyBalance(membersUser1.getMoneyBalance());
        BigDecimal b1 = new BigDecimal(Double.parseDouble(redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Proportional",0)+""));
        BigDecimal b2 = new BigDecimal(Double.parseDouble(scoreDealInfo.getScoreBalance()));
        Double jfbalance = b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        scoreDealInfo.setJfbalance(jfbalance);
        return scoreDealInfo;
    }

    public String getCheckoutMethodList() {
        if (ShiroKit.getUser().getCheckoutMethodList() == null) {
            String checkoutSql = "select id,checkout_method from checkout_method_info where type in ('1','2')"; //获取抵扣方式
            ShiroKit.getUser().setCheckoutMethodList(sqlMapper.selectList(checkoutSql, CheckoutMethodInfo.class));
        }
        String checkoutMethodHtml = "";
        for (int i = 0; i < ShiroKit.getUser().getCheckoutMethodList().size(); i++) {
            checkoutMethodHtml += "<option value='" + ShiroKit.getUser().getCheckoutMethodList().get(i).getId() + "'>" + ShiroKit.getUser().getCheckoutMethodList().get(i).getCheckoutMethod() + "</option>";
        }
        return checkoutMethodHtml;
    }

    public void getCustomerInformationsList() {
        if (ShiroKit.getUser().getOccupationInfoList() == null) {
            String getListSql = "select id, occupation from occupation_info where isshow=1 order by num asc;";
            List<OccupationInfo> occupationList = sqlMapper.selectList(getListSql, OccupationInfo.class);
            ShiroKit.getUser().setOccupationInfoList(occupationList);
        }
        if (ShiroKit.getUser().getRefereeShipInfoList() == null) {
            String getListSql = "select id,referee_ship as refereeShip from referee_ship_info order by num asc;";
            List<RefereeShipInfo> refereeShipList = sqlMapper.selectList(getListSql, RefereeShipInfo.class);
            ShiroKit.getUser().setRefereeShipInfoList(refereeShipList);
        }
    }

    public void getVipLevelName(String reservationsId) {
        String vipLevelName = memberProductService.getVipLevelName(reservationsId);
        String updasql = "update members_user set vip_level_name='" + vipLevelName + "' where reservations_id='" + reservationsId + "'";
        sqlMapper.update(updasql);
    }

}
